/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By 深圳中科鑫智科技有限公司
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.business.annotation.NoRepeatSubmit;
import com.shop.cereshop.business.annotation.NoRepeatWebLog;
import com.shop.cereshop.business.page.order.Product;
import com.shop.cereshop.business.page.order.ShopOrder;
import com.shop.cereshop.business.page.order.ShopOrderExportDTO;
import com.shop.cereshop.business.page.order.ShopOrderStat;
import com.shop.cereshop.business.param.order.OrderBillingParam;
import com.shop.cereshop.business.param.order.OrderDileveryParam;
import com.shop.cereshop.business.param.order.OrderGetAllParam;
import com.shop.cereshop.business.param.order.OrderGetByIdParam;
import com.shop.cereshop.business.service.order.CereOrderDileverService;
import com.shop.cereshop.business.service.order.CereOrderProductAttributeService;
import com.shop.cereshop.business.service.order.CereOrderProductService;
import com.shop.cereshop.business.service.order.CereShopOrderService;
import com.shop.cereshop.business.utils.ContextUtil;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.business.CerePlatformBusiness;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.order.CereOrderProduct;
import com.shop.cereshop.commons.domain.order.CereShopOrder;
import com.shop.cereshop.commons.enums.OrderStateEnum;
import com.shop.cereshop.commons.enums.PaymentModeEnum;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.poi.export.ExcelExportUtils;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.GsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@RestController
@RequestMapping("order")
/**
 * 注解方式生成日志对象，指定topic生成对象类名
 */
@Slf4j(topic = "OrderController")
@Api(value = "订单模块", tags = "订单模块")
public class OrderController {

    @Autowired
    private CereShopOrderService cereShopOrderService;

    @Autowired
    private CereOrderDileverService cereOrderDileverService;

    @Autowired
    private CereOrderProductService cereOrderProductService;

    @Autowired
    private CereOrderProductAttributeService cereOrderProductAttributeService;

    /**
     * 订单数量
     */
    @GetMapping(value = "/total")
    @ApiOperation(value = "订单数量")
    public Result total(Integer state) throws CoBusinessException{
        LambdaQueryWrapper<CereShopOrder> q1 = new LambdaQueryWrapper<>();
        q1.eq(CereShopOrder::getState,state);
        q1.eq(CereShopOrder::getShopId,ContextUtil.getShopId());
        cereShopOrderService.count(q1);
        return new Result(cereShopOrderService.count(q1), CoReturnFormat.SUCCESS);
    }


    /**
     * 提交挂单
     */
    @PostMapping(value = "/addadvanceOrder")
    @ApiOperation(value = "提交挂单")
    public Result addadvanceOrder(@RequestBody OrderBillingParam param) throws CoBusinessException{
        Long shopId = ContextUtil.getShopId();
        param.setShopId(shopId);
        cereShopOrderService.addadvanceOrder(param);
        return new Result(1, CoReturnFormat.SUCCESS);
    }

    /**
     * 修改挂单
     */
    @PostMapping(value = "/update")
    @ApiOperation(value = "修改挂单")
    public Result update(@RequestBody OrderBillingParam param) throws CoBusinessException{
        Long shopId = ContextUtil.getShopId();
        param.setShopId(shopId);
        cereShopOrderService.updateByOrderId(param);
        return new Result(1, CoReturnFormat.SUCCESS);
    }

    /**
     * 更新订单状态
     */
    @PostMapping(value = "/updateState")
    @ApiOperation(value = "更新订单状态")
    public Result updateState(@RequestBody OrderBillingParam param) throws CoBusinessException{

        Long orderId = param.getOrderId();
        if (orderId == null){
            throw new CoBusinessException(CoReturnFormat.ALREADY_NULL);
        }
         CereShopOrder cereShopOrder = new CereShopOrder();
        cereShopOrder.setOrderId(orderId);
        cereShopOrder.setState(param.getState());
        cereShopOrderService.updateById(cereShopOrder);
        return  new Result(1, CoReturnFormat.SUCCESS);
    }

    /**
     * 删除挂单
     */
    @GetMapping(value = "/remove")
    @ApiOperation(value = "删除挂单")
    public Result remove(Long orderId){

        cereShopOrderService.removeById(orderId);
        List<CereOrderProduct> cereOrderProducts = cereOrderProductService.queryByOrderId(orderId);
        for (CereOrderProduct product : cereOrderProducts) {
            cereOrderProductAttributeService.removeByOrderProductId(product.getOrderProductId());
            cereOrderProductService.removeById(product);
        }
        return  new Result(1, CoReturnFormat.SUCCESS);
    }
    /**
     * 获取商品上次拿货价
     */
    @GetMapping(value = "/findLastBuySku")
    @ApiOperation(value = "获取商品上次拿货价")
    public Result findLastBuySku(Long orderId,Long skuId, Long buyerUserId) throws CoBusinessException{
        Long shopId = ContextUtil.getShopId();
        Product lastBuySku = cereShopOrderService.findLastBuySku(orderId, skuId, buyerUserId, shopId);
        return new Result(lastBuySku, CoReturnFormat.SUCCESS);
    }

    /**
     * 订单统计
     */
    @PostMapping(value = "/getShopOrderStat")
    @ApiOperation(value = "订单统计")
    public Result getShopOrderStat(@RequestBody OrderGetAllParam param) throws CoBusinessException{
        Long shopId = ContextUtil.getShopId();
        param.setShopId(shopId);
        return new Result(cereShopOrderService.getShopOrderStat(param), CoReturnFormat.SUCCESS);
    }

    /**
     * 订单管理查询
     * @param param
     * @return
     */
    @PostMapping(value = "getAll")
    @ApiOperation(value = "订单管理查询")
    public Result<Page<ShopOrder>> getAll(@RequestBody OrderGetAllParam param) throws CoBusinessException{
        param.setShopId(ContextUtil.getShopId());
        Page page=cereShopOrderService.getAll(param);
        return new Result(page);
    }

    /**
     * 订单详情查询
     * @param param
     * @return
     */
    @PostMapping(value = "getById")
    @ApiOperation(value = "订单详情查询")
    public Result<ShopOrder> getById(@RequestBody OrderGetByIdParam param) throws CoBusinessException{
        ShopOrder shopOrder=cereShopOrderService.getById(param.getOrderId());
        return new Result(shopOrder);
    }

    /**
     * 发货
     * @param param
     * @return
     */
    @PostMapping(value = "dilevery")
    @NoRepeatSubmit
    @ApiOperation(value = "发货")
    @NoRepeatWebLog
    public Result dilevery(@RequestBody OrderDileveryParam param, HttpServletRequest request) throws CoBusinessException,Exception{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        cereOrderDileverService.dilevery(param,user);
        return new Result(user.getUsername(),"发货", GsonUtil.objectToGson(param));
    }

    /**
     * 订单管理导出
     * @return
     */
    @PostMapping(value = "export")
    @ApiOperation(value = "订单管理导出")
    public void export(@RequestBody OrderGetAllParam param, HttpServletRequest request, HttpServletResponse response) throws CoBusinessException {
        param.setShopId(ContextUtil.getShopId());
        Page<ShopOrder> page =cereShopOrderService.getAll(param);
        List<ShopOrderExportDTO> list = page.getList().stream().map(s -> {
            ShopOrderExportDTO shopOrderExportDTO = new ShopOrderExportDTO();
            shopOrderExportDTO.setOrderId(s.getOrderId());
            shopOrderExportDTO.setCreateTime(s.getCreateTime());
            shopOrderExportDTO.setCustomerName(s.getCustomerName());
            shopOrderExportDTO.setNumber(s.getNumber());
            shopOrderExportDTO.setPrice(s.getPrice());
            shopOrderExportDTO.setPaymentTime(s.getPaymentTime());
            shopOrderExportDTO.setReceiveName(s.getReceiveName());
            shopOrderExportDTO.setReceiveAdress(s.getReceiveAdress());
            shopOrderExportDTO.setReceivePhone(s.getReceivePhone());
            shopOrderExportDTO.setRemark(s.getRemark());
            shopOrderExportDTO.setTransactionId(s.getTransactionId());
            shopOrderExportDTO.setState(OrderStateEnum.getMsgByCode(s.getState()));
            shopOrderExportDTO.setPaymentMode(PaymentModeEnum.getMsgByCode(s.getPaymentMode()));
            if(EmptyUtils.isNotEmpty(s.getProducts())){
                String productNames=s.getProducts().stream().map(Product::getProductName).collect(Collectors.joining(";"));
                shopOrderExportDTO.setProductNames(productNames);
            }
            shopOrderExportDTO.setHistoryOrderNum(s.getTotal());
            return shopOrderExportDTO;

        }).collect(Collectors.toList());
        //定义导出的excel名字
        String excelName = "订单列表";
        ExcelExportUtils.exportExcel(request,response,excelName,list, ShopOrderExportDTO.class);
    }
}
